const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const md5 = require('md5');

// 可配置的盐
const SALT = process.env.SALT || '';

// 用户模型
const UserSchema = new Schema({
  nickName: {
    type: String,
    required: true,
    comment: '用户昵称'
  },
  deptId: {
    type: Schema.Types.ObjectId,
    ref: 'Dept',
    comment: '归属部门'
  },
  phoneNumber: {
    type: String,
    comment: '手机号码'
  },
  userName: {
    type: String,
    required: true,
    unique: true,
    comment: '用户名称（登录标志）'
  },
  password: {
    type: String,
    required: true,
    set: (value) => md5(value + SALT), // 密码加密
    comment: '用户密码（MD5加密）'
  },
  sex: {
    type: String,
    enum: ['男', '女', '未知'],
    default: '未知',
    comment: '用户性别'
  },
  status: {
    type: String,
    enum: ['正常', '停用'],
    default: '正常',
    comment: '状态'
  },
  roles: [{
    type: Schema.Types.ObjectId,
    ref: 'Role',
    comment: '关联的角色'
  }],
  remark: {
    type: String,
    comment: '备注'
  }
});

module.exports = mongoose.model('User', UserSchema);